﻿using System;
using System.Linq;
using DataProcessor.EF;
using Hjt212Parser;
using log4net;

namespace DataProcessor.Process
{
    public static class DataInstructionProcessor
    {
        private static readonly ILog Log = LogManager.GetLogger(typeof(DataInstructionProcessor));

     
        //实时数据指令
        public static void Process2011(string content)
        {
            try
            {
                var mn = Parser.GetStringByKey("MN", content);


                if (mn == null) return;
                if (Util.DontProcess(mn)) return;

                var info = Util.GetInfoFromMn(mn);
                if (info == null)
                {
                    Log.Warn("MN：" + mn + " 找不到对应企业！");
                    return;
                }
                var dataTime = Parser.GetDateTimeByKey("DataTime", content);
                if (dataTime == null) return;
                var pollutantCodes = Parser.GetPollutantCodes(content);
                var masterCode = Util.GetMasterPollutionCode(pollutantCodes);
                if (masterCode == null) return;
                var pollutionInfo = Util.GetContaminantByCode(masterCode);
                if (pollutionInfo == null) return;
                /*using (var contextTarget = new PlatformXpfContext())
                {
                    var beginHour = Util.OffsetMinute(dataTime.Value, -3);
                    var endHour = Util.OffsetMinute(dataTime.Value, 3);
                    var records =
                        contextTarget.主实时数据.Where(
                            t =>
                                t.监测时间 >= beginHour && t.监测时间 < endHour && t.企业基本信息ID == info.EnterpriseID &&
                                t.企业排口ID == info.LetportID).ToList();

                    foreach (主实时数据 record in records)
                    {
                        contextTarget.主实时数据.Remove(record);
                    }
                    contextTarget.SaveChanges();
                }*/
                using (var contextTarget = new PlatformXpfContext())
                {
                    var master = new 主实时数据
                    {
                        企业基本信息ID = info.企业基本信息ID,
                        企业排口ID = info.ID,
                        污染物类别ID = pollutionInfo.污染物类别ID,
                        监测时间 = dataTime.Value
                    };
                    contextTarget.主实时数据.Add(master);

                    var cou = Parser.GetDecimalByKey(masterCode + "-Cou", content);
                    master.累计量 = cou ?? 0;
                    var rtdDouble = Parser.GetDoubleByKey(masterCode + "-Rtd", content);
                    if (rtdDouble == null) return;
                    master.RTD = rtdDouble.Value;
                    foreach (var detailCode in pollutantCodes)
                    {
                        if (detailCode.Equals(masterCode))
                        {
                            continue;
                        }
                        pollutionInfo = Util.GetContaminantByCode(detailCode);
                        if (pollutionInfo == null) continue;
                        rtdDouble = Parser.GetDoubleByKey(detailCode + "-Rtd", content);
                        if (rtdDouble == null) continue;

                        var detail = new 从实时数据
                        {
                            污染物编码ID = pollutionInfo.ID,
                            RTD = rtdDouble.Value,
                            ZSRTD = Parser.GetDoubleByKey(detailCode + "-ZsRtd", content),
                            Flag = Parser.GetStringByKey(detailCode + "-Flag", content)
                        };
                        master.从实时数据.Add(detail);
                    }
                    contextTarget.SaveChanges();
                }
                //Log.Info("处理成功" + "：\r\n" + content);
            }
            catch (Exception ex)
            {
                Log.Error(ex);
                Log.Error(content);
            }
        }
        //分钟数据处理
        public static void Process2051(string content)
        {
            try
            {
                var mn = Parser.GetStringByKey("MN", content);
                if (mn == null) return;
                if (Util.DontProcess(mn)) return;

                var info = Util.GetInfoFromMn(mn);
                if (info == null)
                {
                    Log.Warn("MN：" + mn + " 找不到对应企业！");
                    return;
                }
                var dataTime = Parser.GetDateTimeByKey("DataTime", content);
                if (dataTime == null)
                {
                    Log.Warn("数据时间不对:" + content);
                    return;
                }
                var pollutantCodes = Parser.GetPollutantCodes(content);
                var masterCode = Util.GetMasterPollutionCode(pollutantCodes);
                if (masterCode == null)
                {
                    Log.Warn("没有主污染物代码:" + content);
                    return;
                }
                var pollutionInfo = Util.GetContaminantByCode(masterCode);
                if (pollutionInfo == null)
                {
                    Log.Warn("平台没有主污染物信息:" + content);
                    return;
                }
                /*using (var contextTarget = new PlatformXpfContext())
                {


                    var beginHour = Util.OffsetMinute(dataTime.Value, -5);
                    var endHour = Util.OffsetMinute(dataTime.Value, 5);
                    var records =
                        contextTarget.主分钟数据.Where(
                            t =>
                                t.监测时间 >= beginHour && t.监测时间 < endHour && t.企业基本信息ID == info.EnterpriseID &&
                                t.企业排口ID == info.LetportID).ToList();

                    foreach (主分钟数据 record in records)
                    {
                        contextTarget.主分钟数据.Remove(record);
                    }
                    contextTarget.SaveChanges();
                }*/
                using (var contextTarget = new PlatformXpfContext())
                {
                    var master = new 主分钟数据
                    {
                        企业基本信息ID = info.企业基本信息ID,
                        企业排口ID = info.ID,
                        污染物类别ID = pollutionInfo.污染物类别ID,
                        监测时间 = dataTime.Value,
                        时段量 = ValidData.Process(Parser.GetDoubleByKey(masterCode + "-Cou", content))
                    };
                    contextTarget.主分钟数据.Add(master);

                    foreach (var detailCode in pollutantCodes)
                    {
                        if (detailCode.Equals(masterCode))
                        {
                            continue;
                        }
                        var couDouble = Parser.GetDoubleByKey(detailCode + "-Cou", content);
                        if (couDouble == null) continue;
                        pollutionInfo = Util.GetContaminantByCode(detailCode);
                        if (pollutionInfo == null) continue;

                        var detail = new 从分钟数据
                        {
                            污染物编码ID = pollutionInfo.ID,
                            Cou = couDouble.Value,
                            ZSCou = Parser.GetDoubleByKey(detailCode + "-ZsCou", content),
                            Min = Parser.GetDoubleByKey(detailCode + "-Min", content),
                            ZSMin = Parser.GetDoubleByKey(detailCode + "-ZsMin", content),
                            Avg = Parser.GetDoubleByKey(detailCode + "-Avg", content),
                            ZSAvg = Parser.GetDoubleByKey(detailCode + "-ZsAvg", content),
                            Max = Parser.GetDoubleByKey(detailCode + "-Max", content),
                            ZSMax = Parser.GetDoubleByKey(detailCode + "-ZsMax", content)
                        };
                        master.从分钟数据.Add(detail);
                    }
                    contextTarget.SaveChanges();
                }
                Log.Info("处理成功" + "：\r\n" + content);
            }
            catch (Exception ex)
            {
                Log.Error(ex);
                Log.Error(content);
            }
        }
        //小时数据处理
        public static void Process2061(string content)
        {
            try
            {
                var mn = Parser.GetStringByKey("MN", content);
                if (mn == null) return;
                if (Util.DontProcess(mn)) return;
                var info = Util.GetInfoFromMn(mn);
                if (info == null)
                {
                    Log.Warn("MN：" + mn + " 找不到对应企业！");
                    return;
                }
                var dataTime = Parser.GetDateTimeByKey("DataTime", content);
                if (dataTime == null) return;
                var pollutantCodes = Parser.GetPollutantCodes(content);
                var masterCode = Util.GetMasterPollutionCode(pollutantCodes);
                if (masterCode == null) return;
                var pollutionInfo = Util.GetContaminantByCode(masterCode);
                if (pollutionInfo == null) return;
                using (var contextTarget = new PlatformXpfContext())
                {
                    var beginHour = Util.TrimToHour(dataTime.Value, 0);
                    var endHour = Util.TrimToHour(dataTime.Value, 1);
                    var records =
                        contextTarget.主小时数据.Where(
                            t =>
                                t.监测时间 >= beginHour && t.监测时间 < endHour && t.企业基本信息ID == info.企业基本信息ID &&
                                t.企业排口ID == info.ID).ToList();

                    foreach (主小时数据 record in records)
                    {
                        contextTarget.从小时数据.RemoveRange(record.从小时数据);
                        contextTarget.主小时数据.Remove(record);
                        
                    }
                    contextTarget.SaveChanges();
                }
                using (var contextTarget = new PlatformXpfContext())
                {
                    var master = new 主小时数据
                    {
                        企业基本信息ID = info.企业基本信息ID,
                        企业排口ID = info.ID,
                        污染物类别ID = pollutionInfo.污染物类别ID,
                        监测时间 = dataTime.Value,
                        时段量 = ValidData.Process(Parser.GetDoubleByKey(masterCode + "-Cou", content))
                    };
                    contextTarget.主小时数据.Add(master);

                    foreach (var detailCode in pollutantCodes)
                    {
                        if (detailCode.Equals(masterCode))
                        {
                            continue;
                        }
                        var couDouble = Parser.GetDoubleByKey(detailCode + "-Cou", content);
                        if (couDouble == null) continue;
                        pollutionInfo = Util.GetContaminantByCode(detailCode);
                        if (pollutionInfo == null) continue;

                        var detail = new 从小时数据
                        {
                            污染物编码ID = pollutionInfo.ID,
                            Cou = couDouble.Value,
                            ZSCou = Parser.GetDoubleByKey(detailCode + "-ZsCou", content),
                            Min = Parser.GetDoubleByKey(detailCode + "-Min", content),
                            ZSMin = Parser.GetDoubleByKey(detailCode + "-ZsMin", content),
                            Avg = Parser.GetDoubleByKey(detailCode + "-Avg", content),
                            ZSAvg = Parser.GetDoubleByKey(detailCode + "-ZsAvg", content),
                            Max = Parser.GetDoubleByKey(detailCode + "-Max", content),
                            ZSMax = Parser.GetDoubleByKey(detailCode + "-ZsMax", content)
                        };
                        master.从小时数据.Add(detail);
                    }
                    contextTarget.SaveChanges();
                }
                Log.Info("处理成功" + "：\r\n" + content);
            }
            catch (Exception ex)
            {
                Log.Error(ex);
                Log.Error(content);
            }
        }
        //日处理数据，并同步月处理数据，年处理数据
        public static void Process2031(string content)
        {
            try
            {
                var mn = Parser.GetStringByKey("MN", content);
                if (mn == null) return;
                if (Util.DontProcess(mn)) return;
                var info = Util.GetInfoFromMn(mn);
                if (info == null)
                {
                    Log.Warn("MN：" + mn + " 找不到对应企业！");
                    return;
                }
                var dataTime = Parser.GetDateTimeByKey("DataTime", content);
                if (dataTime == null) return;
                var pollutantCodes = Parser.GetPollutantCodes(content);
                var masterCode = Util.GetMasterPollutionCode(pollutantCodes);
                if (masterCode == null) return;
                var pollutionInfo = Util.GetContaminantByCode(masterCode);
                if (pollutionInfo == null) return;
                var beginDay = Util.TrimToDay(dataTime.Value, 0);
                var endDay = Util.TrimToDay(dataTime.Value, 1);
                using (var contextTarget = new PlatformXpfContext())
                {
                    var records = contextTarget.主日数据.Where(t => t.监测时间 >= beginDay && t.监测时间 < endDay && t.企业基本信息ID == info.企业基本信息ID && t.企业排口ID == info.ID).ToList();
                    foreach (主日数据 record in records)
                    {
                        contextTarget.从日数据.RemoveRange(record.从日数据);
                        contextTarget.主日数据.Remove(record);
                    }
                    contextTarget.SaveChanges();

                }
                using (var contextTarget = new PlatformXpfContext())
                {
                    var master = new 主日数据
                    {
                        企业基本信息ID = info.企业基本信息ID,
                        企业排口ID = info.ID,
                        污染物类别ID = pollutionInfo.污染物类别ID,
                        监测时间 = dataTime.Value,
                        时段量 = ValidData.Process(Parser.GetDoubleByKey(masterCode + "-Cou", content))
                    };
                    contextTarget.主日数据.Add(master);

                    foreach (var detailCode in pollutantCodes)
                    {
                        if (detailCode.Equals(masterCode))
                        {
                            continue;
                        }
                        var couDouble = Parser.GetDoubleByKey(detailCode + "-Cou", content);
                        if (couDouble == null) continue;
                        pollutionInfo = Util.GetContaminantByCode(detailCode);
                        if (pollutionInfo == null) continue;

                        var detail = new 从日数据
                        {
                            污染物编码ID = pollutionInfo.ID,
                            Cou = couDouble.Value,
                            ZSCou = Parser.GetDoubleByKey(detailCode + "-ZsCou", content),
                            Min = Parser.GetDoubleByKey(detailCode + "-Min", content),
                            ZSMin = Parser.GetDoubleByKey(detailCode + "-ZsMin", content),
                            Avg = Parser.GetDoubleByKey(detailCode + "-Avg", content),
                            ZSAvg = Parser.GetDoubleByKey(detailCode + "-ZsAvg", content),
                            Max = Parser.GetDoubleByKey(detailCode + "-Max", content),
                            ZSMax = Parser.GetDoubleByKey(detailCode + "-ZsMax", content)
                        };
                        master.从日数据.Add(detail);


                    }
                    contextTarget.SaveChanges();
                    Log.Info("处理成功" + "：\r\n" + content);
                }
            }
            catch (Exception ex)
            {
                Log.Error(ex);
                Log.Error(content);
            }
        }
        //日处理数据，并同步月处理数据，年处理数据
        public static void Process2031Month(string content)
        {
            try
            {
                var mn = Parser.GetStringByKey("MN", content);
                if (mn == null) return;
                var info = Util.GetInfoFromMn(mn);
                if (info == null)
                {
                    Log.Warn("MN：" + mn + " 找不到对应企业！");
                    return;
                }
                var dataTime = Parser.GetDateTimeByKey("DataTime", content);
                if (dataTime == null) return;
                var pollutantCodes = Parser.GetPollutantCodes(content);
                var masterCode = Util.GetMasterPollutionCode(pollutantCodes);
                if (masterCode == null) return;
                var pollutionInfo = Util.GetContaminantByCode(masterCode);
                if (pollutionInfo == null) return;

                using (var contextTarget = new PlatformXpfContext())
                {
                    var monthRecords = contextTarget.主月数据.Where(t =>
                        t.企业基本信息ID == info.企业基本信息ID &&
                        t.企业排口ID == info.ID &&
                        t.监测时间.Year == dataTime.Value.Year &&
                        t.监测时间.Month == dataTime.Value.Month).ToList();

                    foreach (var monthRecord in monthRecords)
                    {
                        contextTarget.从月数据.RemoveRange(monthRecord.从月数据);
                        contextTarget.主月数据.Remove(monthRecord);
                    }
                    contextTarget.SaveChanges();
                }
                using (var contextTarget = new PlatformXpfContext())
                {
                    var monthData = new 主月数据
                    {
                        企业基本信息ID = info.企业基本信息ID,
                        企业排口ID = info.ID,
                        监测时间 = dataTime.Value,
                        污染物类别ID = pollutionInfo.污染物类别ID,
                        时段量 = 0
                    };
                    contextTarget.主月数据.Add(monthData);

                    var beginMonth = Util.TrimToMonth(dataTime.Value, 0);
                    var endMonth = Util.TrimToMonth(dataTime.Value, 1);
                    var records = contextTarget.主日数据.Where(t => t.监测时间 >= beginMonth && t.监测时间 < endMonth && t.企业基本信息ID == info.企业基本信息ID && t.企业排口ID == info.ID).ToList();

                    foreach (var record in records)
                    {
                        monthData.时段量 += record.时段量;
                    }
                    foreach (var detailCode in pollutantCodes)
                    {
                        if (detailCode.Equals(masterCode))
                        {
                            continue;
                        }
                        pollutionInfo = Util.GetContaminantByCode(detailCode);
                        if (pollutionInfo == null) continue;
                        var monthDetail = new 从月数据
                        {
                            污染物编码ID = pollutionInfo.ID,
                            Cou = 0,
                            Avg = Parser.GetDoubleByKey(detailCode + "-Avg", content),
                            Max = double.MinValue,
                            Min = double.MaxValue,
                            ZSCou = 0,
                            ZSMax = double.MinValue,
                            ZSAvg = Parser.GetDoubleByKey(detailCode + "-ZsAvg", content),
                            ZSMin = double.MaxValue,
                        };
                        foreach (var record in records)
                        {
                            foreach (var d in record.从日数据)
                            {
                                if (d.污染物编码ID == monthDetail.污染物编码ID)
                                {
                                    monthDetail.Cou += d.Cou;
                                    if (d.Max != null && d.Max > monthDetail.Max) monthDetail.Max = d.Max;
                                    if (d.Min != null && d.Min < monthDetail.Min) monthDetail.Min = d.Min;
                                    monthDetail.Avg = (!monthData.时段量.HasValue || monthData.时段量 == 0) ? 0 : monthDetail.Cou * 1000 / monthData.时段量;
                                    if (d.ZSCou != null)
                                    {
                                        monthDetail.ZSCou += d.ZSCou;
                                        if (d.ZSMax != null && d.ZSMax > monthDetail.ZSMax) monthDetail.ZSMax = d.ZSMax;
                                        if (d.ZSMin != null && d.ZSMin < monthDetail.ZSMin) monthDetail.ZSMin = d.ZSMin;
                                        monthDetail.ZSAvg = (!monthData.时段量.HasValue || monthData.时段量 == 0)
                                            ? 0
                                            : monthDetail.ZSAvg * 1000 / monthData.时段量;
                                    }
                                }
                            }
                        }
                        monthData.从月数据.Add(monthDetail);
                    }
                    contextTarget.SaveChanges();
                    Log.Info("处理成功：" + content);
                }
            }
            catch (Exception ex)
            {
                Log.Error(ex);
                Log.Error(content);
            }
        }
        //日处理数据，并同步月处理数据，年处理数据
        public static void Process2031Year(string content)
        {
            try
            {
                var mn = Parser.GetStringByKey("MN", content);
                if (mn == null) return;
                var info = Util.GetInfoFromMn(mn);
                if (info == null)
                {
                    Log.Warn("MN：" + mn + " 找不到对应企业！");
                    return;
                }
                var dataTime = Parser.GetDateTimeByKey("DataTime", content);
                if (dataTime == null) return;
                var pollutantCodes = Parser.GetPollutantCodes(content);
                var masterCode = Util.GetMasterPollutionCode(pollutantCodes);
                if (masterCode == null) return;
                var pollutionInfo = Util.GetContaminantByCode(masterCode);
                if (pollutionInfo == null) return;

                using (var contextTarget = new PlatformXpfContext())
                {
                    var monthRecords = contextTarget.主年数据.Where(t =>
                        t.企业基本信息ID == info.企业基本信息ID &&
                        t.企业排口ID == info.ID &&
                        t.监测时间.Year == dataTime.Value.Year).ToList();

                    foreach (var monthRecord in monthRecords)
                    {
                        contextTarget.从年数据.RemoveRange(monthRecord.从年数据);
                        contextTarget.主年数据.Remove(monthRecord);
                    }
                    contextTarget.SaveChanges();
                }
                using (var contextTarget = new PlatformXpfContext())
                {
                    var monthData = new 主年数据
                    {
                        企业基本信息ID = info.企业基本信息ID,
                        企业排口ID = info.ID,
                        监测时间 = dataTime.Value,
                        污染物类别ID = pollutionInfo.污染物类别ID,
                        时段量 = 0
                    };
                    contextTarget.主年数据.Add(monthData);

                    var beginMonth = Util.TrimToYear(dataTime.Value, 0);
                    var endMonth = Util.TrimToYear(dataTime.Value, 1);
                    var records = contextTarget.主月数据.Where(t => t.监测时间 >= beginMonth && t.监测时间 < endMonth && t.企业基本信息ID == info.企业基本信息ID && t.企业排口ID == info.ID).ToList();

                    foreach (var record in records)
                    {
                        monthData.时段量 += record.时段量.HasValue ? record.时段量.Value : 0;
                    }
                    foreach (var detailCode in pollutantCodes)
                    {
                        if (detailCode.Equals(masterCode))
                        {
                            continue;
                        }
                        pollutionInfo = Util.GetContaminantByCode(detailCode);
                        if (pollutionInfo == null) continue;
                        var monthDetail = new 从年数据
                        {
                            污染物编码ID = pollutionInfo.ID,
                            Cou = 0,
                            Avg = Parser.GetDoubleByKey(detailCode + "-Avg", content),
                            Max = double.MinValue,
                            Min = double.MaxValue,
                            ZSCou = 0,
                            ZSMax = double.MinValue,
                            ZSAvg = Parser.GetDoubleByKey(detailCode + "-ZsAvg", content),
                            ZSMin = double.MaxValue,
                        };
                        foreach (var record in records)
                        {
                            foreach (var d in record.从月数据)
                            {
                                if (d.污染物编码ID == monthDetail.污染物编码ID)
                                {
                                    monthDetail.Cou += d.Cou;
                                    if (d.Max != null && d.Max > monthDetail.Max) monthDetail.Max = d.Max;
                                    if (d.Min != null && d.Min < monthDetail.Min) monthDetail.Min = d.Min;
                                    monthDetail.Avg = Math.Abs(monthData.时段量) < 0.000001 ? 0 : monthDetail.Cou * 1000 / monthData.时段量;
                                    if (d.ZSCou.HasValue)
                                    {
                                        monthDetail.ZSCou += d.ZSCou;
                                        if (d.ZSMax != null && d.ZSMax > monthDetail.ZSMax) monthDetail.ZSMax = d.ZSMax;
                                        if (d.ZSMin != null && d.ZSMin < monthDetail.ZSMin) monthDetail.ZSMin = d.ZSMin;
                                        monthDetail.ZSAvg = Math.Abs(monthData.时段量) < 0.000001
                                            ? 0
                                            : monthDetail.ZSAvg * 1000 / monthData.时段量;
                                    }
                                }
                            }
                        }
                        monthData.从年数据.Add(monthDetail);
                    }
                    contextTarget.SaveChanges();
                    Log.Info("处理成功：" + content);
                }
            }
            catch (Exception ex)
            {
                Log.Error(ex);
                Log.Error(content);
            }
        }
    }
}
